import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import HomeView from '../views/HomeView.vue'
import PublicActivitiesView from '../views/PublicActivitiesView.vue'
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue'
import ActivityManagementView from '../views/ActivityManagementView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    },
    {
      path: '/public-activities',
      name: 'public-activities',
      component: PublicActivitiesView,
      meta: { requiresAuth: true }
    },
    {
      path: '/public-activities/:id',
      name: 'public-activity-detail',
      component: PublicActivityDetailView,
      meta: { requiresAuth: true }
    },
    {
      path: '/activity-management',
      name: 'activity-management',
      component: ActivityManagementView,
      meta: { requiresAuth: true, isAdmin: true }
    }
  ]
})
router.beforeEach((to, from, next) => {
  const role = localStorage.getItem('role')
  if (to.meta.requiresAuth &&!role) {
    next('/login')
  } else if (to.meta.isAdmin && role!== 'admin') {
    alert('无权限访问')
    next('/')
  } else {
    next()
  }
})

export default router